package com.dragon.app.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.FileChannel;
import java.util.concurrent.Future;
import java.util.concurrent.locks.LockSupport;

/**
 * @Author: longtao
 * @Date: 2019/5/29
 * @Version: 1.0
 * @Description:
 */
public class NIOTest {


    public static void main(String[] args) throws Exception {


        Future future;

        AsynchronousSocketChannel asynchronousSocketChannel;



        nioCopyFile("D:\\01软件\\办公软件\\cn_visio_professional_2016_x86_x64_dvd_6970929.iso","C:\\Users\\SmallDragon\\Desktop\\新建文件夹\\ff.ios");

    }


    /**
     * @param resource
     * @param destination
     * @throws IOException
     */
    public static void nioCopyFile(String resource, String destination)
            throws IOException {
        FileInputStream fis = new FileInputStream(resource);
        FileOutputStream fos = new FileOutputStream(destination);
        FileChannel readChannel = fis.getChannel(); // 读文件通道
        FileChannel writeChannel = fos.getChannel(); // 写文件通道
        ByteBuffer buffer = ByteBuffer.allocate(102400); // 读入数据缓存
        while (true) {
            buffer.clear();
            int len = readChannel.read(buffer); // 读入数据
            if (len == -1) {
                break; // 读取完毕
            }
            buffer.flip();
            writeChannel.write(buffer); // 写入文件
        }
        readChannel.close();
        writeChannel.close();
    }


    /**
     * 文件内存映射
     * 对MappedByteBuffer的修改就相当于修改文件本身，这样操作的速度是很快的。
     */
    public void fileMapped() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("C:\\mapfile.txt", "rw");
        FileChannel fc = raf.getChannel();
        // 将文件映射到内存中
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
        while (mbb.hasRemaining()) {
            System.out.print((char) mbb.get());
        }
        mbb.put(0, (byte) 98); // 修改文件
        raf.close();
    }





}
